<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="google-site-verification" content="_hgg1Y3vl6FDA0y9ycG3MRMdmBljtivpN0MGPBl9Vks">
  <meta name="baidu-site-verification" content="code-BjkBUVTz39">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wangduwei.top","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":true,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"gitalk | valine","storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

<script data-ad-client="ca-pub-8087648226243491" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

  <meta name="description" content="一、概述代码是解决问题的工具。当通过编码方式解决一个问题时，通常有如下步骤：  定义问题 设计解决方案 编码实现方案 测试程序  编码实现通常是我们利用计算机高级语言书写的，符合一定逻辑的程序代码，这种含逻辑的代码计算机是无法理解的，它能理解的只是一条条由0和1组成的指令即机器语言。所以这就涉及从高级语言到机器语言的翻译和转换过程，处理这个过程的程序叫编译器。 编译器这个程序，很庞大很复杂，为了让">
<meta property="og:type" content="article">
<meta property="og:title" content="ELF文件的结构">
<meta property="og:url" content="https://wangduwei.top/file-format-elf.html">
<meta property="og:site_name" content="嗅不到北的狗子">
<meta property="og:description" content="一、概述代码是解决问题的工具。当通过编码方式解决一个问题时，通常有如下步骤：  定义问题 设计解决方案 编码实现方案 测试程序  编码实现通常是我们利用计算机高级语言书写的，符合一定逻辑的程序代码，这种含逻辑的代码计算机是无法理解的，它能理解的只是一条条由0和1组成的指令即机器语言。所以这就涉及从高级语言到机器语言的翻译和转换过程，处理这个过程的程序叫编译器。 编译器这个程序，很庞大很复杂，为了让">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://wangduwei.top/images/GCC_CompilationProcess.png">
<meta property="og:image" content="https://wangduwei.top/images/elf_format_overview.jpeg">
<meta property="og:image" content="https://wangduwei.top/images/elf_string_table.jpeg">
<meta property="article:published_time" content="2021-08-30T07:22:49.000Z">
<meta property="article:modified_time" content="2021-10-30T07:11:19.874Z">
<meta property="article:author" content="wangduwei">
<meta property="article:tag" content="File">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://wangduwei.top/images/GCC_CompilationProcess.png">

<link rel="canonical" href="https://wangduwei.top/file-format-elf.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>ELF文件的结构 | 嗅不到北的狗子</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-69Z1P1CBTV"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'G-69Z1P1CBTV');
      }
    </script>


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?9f3c7bb2232e1e3fda4c019e4a4406c0";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="嗅不到北的狗子" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">嗅不到北的狗子</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-sitemap">

    <a href="/sitemap.xml" rel="section"><i class="fa fa-sitemap fa-fw"></i>站点地图</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangduwei.top/file-format-elf.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpeg">
      <meta itemprop="name" content="wangduwei">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="嗅不到北的狗子">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          ELF文件的结构
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-08-30 15:22:49" itemprop="dateCreated datePublished" datetime="2021-08-30T15:22:49+08:00">2021-08-30</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-10-30 15:11:19" itemprop="dateModified" datetime="2021-10-30T15:11:19+08:00">2021-10-30</time>
              </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/file-format-elf.html#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/file-format-elf.html" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>5.9k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>5 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h4 id="一、概述"><a href="#一、概述" class="headerlink" title="一、概述"></a>一、概述</h4><p>代码是解决问题的工具。当通过编码方式解决一个问题时，通常有如下步骤：</p>
<ul>
<li>定义问题</li>
<li>设计解决方案</li>
<li>编码实现方案</li>
<li>测试程序</li>
</ul>
<p>编码实现通常是我们利用计算机高级语言书写的，符合一定逻辑的程序代码，这种含逻辑的代码计算机是无法理解的，它能理解的只是一条条由0和1组成的指令即机器语言。所以这就涉及从高级语言到机器语言的翻译和转换过程，处理这个过程的程序叫编译器。</p>
<p>编译器这个程序，很庞大很复杂，为了让它简洁，好控制，我们把它拆成四个部分：</p>
<ul>
<li>预处理器</li>
<li>编译器</li>
<li>汇编器</li>
<li>链接器</li>
</ul>
<p>每一个阶段基本上都是在为下一个阶段做准备，它的过程如下图所示：</p>
<center>
    <img src="../images/GCC_CompilationProcess.png" width="500"/>
</center>

<p>预处理器（Preprocessor）处理代码的过程叫预处理阶段，它所做的工作包括：</p>
<ul>
<li>#define宏定义展开</li>
<li>处理条件编译指令</li>
<li>处理#include指令</li>
<li>删除注释</li>
<li>添加行号</li>
<li>保留#pragma指令</li>
</ul>
<p>编译器（Compiler）处理代码的过程叫编译，它主要是将上一步的产物转换成汇编代码，它的工作内容包括：</p>
<ul>
<li>词法分析</li>
<li>语法分析</li>
<li>语义分析</li>
<li>优化</li>
</ul>
<p>汇编器（Assembler）处理代码的过程叫汇编过程，它主要将汇编代码转换成二进制的机器码</p>
<ul>
<li>汇编码到机器码的翻译</li>
</ul>
<p>链接器（Linker）处理代码的过程叫链接过程，多个文件合并成一个文件</p>
<ul>
<li>空间与地址分配-相同部分合并</li>
<li>符号解析和重定位-合并后位置（偏移量）调整</li>
</ul>
<p>综上可知，目标文件是程序未链接前的一个中间文件。目标文件内容的存储方式符合ELF文件标准，所以他是一种特殊的ELF文件。</p>
<h4 id="二、文件结构解析"><a href="#二、文件结构解析" class="headerlink" title="二、文件结构解析"></a>二、文件结构解析</h4><p>目标文件其实是ELF文件的一种，常见的ELF文件还有.so和.oat文件等。ELF文件存在两种观察角度，分别是编译角度和运行角度。编译角度是指，在代码编译阶段的存储格式。运行角度是指，文件被加载进内存时的存储当时。<br>两个角度看到的结构略有差异。如图：</p>
<center>
    <img src="../images/elf_format_overview.jpeg" width="500"/>
</center>

<p>从图中可以得到这样一些信息：Program Header Table对于编译视图是可选的，因为它只在程序被加载进内存时使用到。Section Header Table对于执行视图是可选的。<br>编译视图是以section为组织单位，执行视图是以segment为组织单位（多个section会被映射到同一个segment），下面介绍一些重要的结构。</p>
<h5 id="ELF-Header-文件的总体结构"><a href="#ELF-Header-文件的总体结构" class="headerlink" title="ELF Header-文件的总体结构"></a>ELF Header-文件的总体结构</h5><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">#define EI_NIDENT 16</span><br><span class="line">typedef struct &#123;</span><br><span class="line">    unsigned char e_ident[EI_NIDENT];</span><br><span class="line">    Elf32_Half e_type;               /* 此elf文件的类型见下表  */</span><br><span class="line">    Elf32_Half e_machine;            /* CPU平台架构  */</span><br><span class="line">    Elf32_Word e_version;            /* 此文件的版本  */</span><br><span class="line">    Elf32_Addr e_entry;              /* 加载完该程序后的执行入口  */</span><br><span class="line">    Elf32_Off e_phoff;               /* program header table在文件中的偏移量  */</span><br><span class="line">    Elf32_Off e_shoff;               /* section header table在此文件中的偏移量 */</span><br><span class="line">    Elf32_Word e_flags;              /* processor-specific flags associated with the file */</span><br><span class="line">    Elf32_Half e_ehsize;             /* the ELF header&#x27;s size in bytes. */</span><br><span class="line">    Elf32_Half e_phentsize;          /* program-header-table数组中一个元素的大小 */</span><br><span class="line">    Elf32_Half e_phnum;              /* program-header-table数组元素的个数 */</span><br><span class="line">    Elf32_Half e_shentsize;          /* section header table数组中一个元素的大小 */</span><br><span class="line">    Elf32_Half e_shnum;              /* section header table包含的元素个数 */</span><br><span class="line">    Elf32_Half e_shstrndx;           /* the section header table index of the entry associated with the section name string table. */</span><br><span class="line"> &#125; Elf32_Ehdr;</span><br></pre></td></tr></table></figure>

<table>
<thead>
<tr>
<th>文件类型</th>
<th>类型描述</th>
</tr>
</thead>
<tbody><tr>
<td>ET_NONE</td>
<td>未知类型。这个标记表明文件类型不确定，或者还未定义。</td>
</tr>
<tr>
<td>ET_REL</td>
<td>重定位文件。 ELF 类型标记为 relocatable 意味着该文件被标记为了一段可重定位的代码，有时也称为目标文件。可重定位 目标文件通常是还未被链接到可执行程序的一段位置独立的代码 （position independent code）。 在编译完代码之后通常可以看到一 个.o 格式的文件， 这种文件包含了创建可执行文件所需要的代码 和数据。</td>
</tr>
<tr>
<td>ET_EXEC</td>
<td>可执行文件。ELF 类型为 executable，表明这个文件被标 记为可执行文件。这种类型的文件也称为程序，是一个进程开始执 行的入口。</td>
</tr>
<tr>
<td>ET_DYN</td>
<td>共享目标文件。ELF 类型为 dynamic，意味着该文件被标记 为了一个动态的可链接的目标文件，也称为共享库。这类共享库会在 程序运行时被装载并链接到程序的进程镜像中。</td>
</tr>
<tr>
<td>ET_CORE</td>
<td>核心文件。在程序崩溃或者进程传递了一个 SIGSEGV 信 号（分段违规）时，会在核心文件中记录整个进程的镜像信息。可以 使用 GDB 读取这类文件来辅助调试并查找程序崩溃的原因。</td>
</tr>
</tbody></table>
<h5 id="Program-Header-Table"><a href="#Program-Header-Table" class="headerlink" title="Program Header Table"></a>Program Header Table</h5><p>程序装载时，根据此结构的信息对文件进行分段（segment）。描述了磁盘上可执行文件的内存布局以及如何映射到内存中。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">typedef struct &#123;</span><br><span class="line">   uint32_t   p_type;   /* 此元素描述的是哪种segment，以及如何解析  */</span><br><span class="line">   Elf32_Off  p_offset; /* segment首字节在文件中的偏移值  */</span><br><span class="line">   Elf32_Addr p_vaddr;  /* 应该加载到内存中的哪个虚拟地址中  */</span><br><span class="line">   Elf32_Addr p_paddr;  /* 相关的物理地址，BSD中为0  */</span><br><span class="line">   uint32_t   p_filesz; /* 文件的字节数  */</span><br><span class="line">   uint32_t   p_memsz;  /* 加载到内存中的字节数  */</span><br><span class="line">   uint32_t   p_flags;  /* segment类型标志位  */</span><br><span class="line">   uint32_t   p_align;  /* 内存对其  */</span><br><span class="line">&#125; Elf32_Phdr;</span><br></pre></td></tr></table></figure>

<table>
<thead>
<tr>
<th>p_flags</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>PF_X</td>
<td>An executable segment.</td>
</tr>
<tr>
<td>PF_W</td>
<td>An executable segment.</td>
</tr>
<tr>
<td>PF_R</td>
<td>A readable segment.</td>
</tr>
</tbody></table>
<h5 id="Section-Header-Table"><a href="#Section-Header-Table" class="headerlink" title="Section Header Table"></a>Section Header Table</h5><p>用于定位文件中所有的section，主要用于链接和调试，没有Section Header Table程序仍然可以正常运行，因为它没有对内存布局进行描述，它是一个元素为Elf32_Shdr的数组结构。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">typedef struct</span><br><span class="line">&#123;</span><br><span class="line">	Elf32_Word sh_name;      /* Section name (string tbl index)   */</span><br><span class="line">	Elf32_Word sh_type;      /* Section type                      */</span><br><span class="line">	Elf32_Word sh_flags;     /* Section flags                     */</span><br><span class="line">	Elf32_Addr sh_addr;      /* Section virtual addr at execution */</span><br><span class="line">	Elf32_Off sh_offset;     /* Section file offset               */</span><br><span class="line">	Elf32_Word sh_size;      /* Section size in bytes             */</span><br><span class="line">	Elf32_Word sh_link;      /* Link to another section           */</span><br><span class="line">	Elf32_Word sh_info;      /* Additional section information    */</span><br><span class="line">	Elf32_Word sh_addralign; /* Section alignment                 */</span><br><span class="line">	Elf32_Word sh_entsize;   /* Entry size if section holds table */</span><br><span class="line">&#125; Elf32_Shdr;</span><br></pre></td></tr></table></figure>

<table>
<thead>
<tr>
<th>Section type</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>SHT_NULL</td>
<td>This value marks the section header as inactive. It does not have an associated section.  Other members of the section header have undefined values.</td>
</tr>
<tr>
<td>SHT_PROGBITS</td>
<td>This section holds information defined by the program, whose format and meaning are determined solely by the program.</td>
</tr>
<tr>
<td>SHT_SYMTAB</td>
<td>This section holds a symbol table.  Typically, SHT_SYMTAB provides symbols for link editing, though it may also be used for dynamic linking.  As a complete symbol table, it may contain many symbols unnecessary for dynamic linking.  An object file can also contain a SHT_DYNSYM section.</td>
</tr>
<tr>
<td>SHT_STRTAB</td>
<td>This section holds a string table.  An object file may have multiple string table sections.</td>
</tr>
<tr>
<td>SHT_RELA</td>
<td>This section holds relocation entries with explicit addends, such as type Elf32_Rela for the 32-bit class of object files.  An object may have multiple relocation sections.</td>
</tr>
<tr>
<td>SHT_HASH</td>
<td>This section holds a symbol hash table.  An object participating in dynamic linking must contain a symbol hash table.  An object file may have only one hash table.</td>
</tr>
<tr>
<td>SHT_DYNAMIC</td>
<td>This section holds information for dynamic linking. An object file may have only one dynamic section.</td>
</tr>
<tr>
<td>SHT_NOTE</td>
<td>This section holds notes (ElfN_Nhdr).</td>
</tr>
<tr>
<td>SHT_NOBITS</td>
<td>A section of this type occupies no space in the  file but otherwise resembles SHT_PROGBITS. Although this section contains no bytes, the sh_offset member contains the conceptual file offset.</td>
</tr>
<tr>
<td>SHT_REL</td>
<td>This section holds relocation offsets without explicit addends, such as type Elf32_Rel for the 32-bit class of object files.  An object file may have multiple relocation sections.</td>
</tr>
<tr>
<td>SHT_SHLIB</td>
<td>This section is reserved but has unspecified semantics.</td>
</tr>
<tr>
<td>SHT_DYNSYM</td>
<td>This section holds a minimal set of dynamic linking symbols.  An object file can also contain a SHT_SYMTAB section.</td>
</tr>
<tr>
<td>SHT_LOPROC, SHT_HIPROC</td>
<td>Values in the inclusive range [SHT_LOPROC, SHT_HIPROC] are reserved for processor-specific semantics.</td>
</tr>
<tr>
<td>SHT_LOUSER</td>
<td>This value specifies the lower bound of the range of indices reserved for application programs.</td>
</tr>
<tr>
<td>SHT_HIUSER</td>
<td>This value specifies the upper bound of the range of indices reserved for application programs. Section types between SHT_LOUSER and SHT_HIUSER may be used by the application, without conflicting with current or future system-defined section types.</td>
</tr>
</tbody></table>
<h5 id="字符串表和符号表（String-and-symbol-tables）"><a href="#字符串表和符号表（String-and-symbol-tables）" class="headerlink" title="字符串表和符号表（String and symbol tables）"></a>字符串表和符号表（String and symbol tables）</h5><p>存放scetion的名字，以及符号信息。其他结构通过index访问此结构中的字符串信息。符号表保存了用于定位符号引用的信息。它是以下结构的数组：</p>
<center>
    <img src="../images/elf_string_table.jpeg" width="500"/>
</center>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">typedef struct &#123;</span><br><span class="line">       uint32_t      st_name;</span><br><span class="line">       Elf32_Addr    st_value;</span><br><span class="line">       uint32_t      st_size;</span><br><span class="line">       unsigned char st_info;</span><br><span class="line">       unsigned char st_other;</span><br><span class="line">       uint16_t      st_shndx;</span><br><span class="line">&#125; Elf32_Sym;</span><br></pre></td></tr></table></figure>


<h5 id="Relocation-entries-Rel-amp-Rela"><a href="#Relocation-entries-Rel-amp-Rela" class="headerlink" title="Relocation entries (Rel &amp; Rela)"></a>Relocation entries (Rel &amp; Rela)</h5><p>重定位是连接符号引用（函数的名字）和符号定义（函数的定义、函数的实现）的过程。重定位文件必须包含如何修改section内容的信息，来让执行文件或共享目标文件正确的调用外部函数。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">typedef struct &#123;</span><br><span class="line">        Elf32_Addr      r_offset;</span><br><span class="line">        Elf32_Word      r_info;</span><br><span class="line">&#125; Elf32_Rel;</span><br><span class="line"> </span><br><span class="line">typedef struct &#123;</span><br><span class="line">        Elf32_Addr      r_offset;</span><br><span class="line">        Elf32_Word      r_info;</span><br><span class="line">        Elf32_Sword     r_addend;</span><br><span class="line">&#125; Elf32_Rela;</span><br></pre></td></tr></table></figure>
<p>r_offset：<br>对于重定位文件来说，此值表示从section的开始到被修改值在section中的偏移量。<br>对于执行文件和共享库文件来说，此值表示需要被重定位的虚拟地址。</p>
<p>r_info：<br>符号表的index和重定位的类型。</p>
<p>r_addend：<br>用于计算重定位字段的值。</p>
<h4 id="三、参考链接"><a href="#三、参考链接" class="headerlink" title="三、参考链接"></a>三、参考链接</h4><p><a target="_blank" rel="noopener" href="https://www.man7.org/linux/man-pages/man5/elf.5.html">Linux manual page</a><br><a target="_blank" rel="noopener" href="https://www.codetd.com/article/489055">The structure of an ARM ELF image</a><br><a target="_blank" rel="noopener" href="https://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html">Compiling, Linking and Building</a></p>

    </div>

    
    
    
        <div class="reward-container">
  <div>赏你一杯咖啡</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.png" alt="wangduwei 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.jpeg" alt="wangduwei 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>wangduwei
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://wangduwei.top/file-format-elf.html" title="ELF文件的结构">https://wangduwei.top/file-format-elf.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/File/" rel="tag"># File</a>
          </div>

        
  <div class="post-widgets">
    <div class="wp_rating">
      <div id="wpac-rating"></div>
    </div>
  </div>


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/file-format-class.html" rel="prev" title="Class文件的存储格式">
      <i class="fa fa-chevron-left"></i> Class文件的存储格式
    </a></div>
      <div class="post-nav-item">
    <a href="/base-economic-concept.html" rel="next" title="市盈率和市净率">
      市盈率和市净率 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
      <div class="tabs tabs-comment">
        <ul class="nav-tabs">
            <li class="tab"><a href="#comment-gitalk">gitalk</a></li>
            <li class="tab"><a href="#comment-valine">valine</a></li>
        </ul>
        <div class="tab-content">
            <div class="tab-pane gitalk" id="comment-gitalk">
              <div class="comments" id="gitalk-container"></div>
            </div>
            <div class="tab-pane valine" id="comment-valine">
              <div class="comments" id="valine-comments"></div>
            </div>
        </div>
      </div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">一、概述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E6%96%87%E4%BB%B6%E7%BB%93%E6%9E%84%E8%A7%A3%E6%9E%90"><span class="nav-number">2.</span> <span class="nav-text">二、文件结构解析</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#ELF-Header-%E6%96%87%E4%BB%B6%E7%9A%84%E6%80%BB%E4%BD%93%E7%BB%93%E6%9E%84"><span class="nav-number">2.1.</span> <span class="nav-text">ELF Header-文件的总体结构</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Program-Header-Table"><span class="nav-number">2.2.</span> <span class="nav-text">Program Header Table</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Section-Header-Table"><span class="nav-number">2.3.</span> <span class="nav-text">Section Header Table</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E8%A1%A8%E5%92%8C%E7%AC%A6%E5%8F%B7%E8%A1%A8%EF%BC%88String-and-symbol-tables%EF%BC%89"><span class="nav-number">2.4.</span> <span class="nav-text">字符串表和符号表（String and symbol tables）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Relocation-entries-Rel-amp-Rela"><span class="nav-number">2.5.</span> <span class="nav-text">Relocation entries (Rel &amp; Rela)</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="nav-number">3.</span> <span class="nav-text">三、参考链接</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="wangduwei"
      src="/images/avatar.jpeg">
  <p class="site-author-name" itemprop="name">wangduwei</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/duweiwang" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;duweiwang" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wangduwei8@gmail.com" title="E-Mail → mailto:wangduwei8@gmail.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wangduwei</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">53k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">48 分钟</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/medium-zoom@1/dist/medium-zoom.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>



  <script>
  if (CONFIG.page.isPost) {
    wpac_init = window.wpac_init || [];
    wpac_init.push({
      widget: 'Rating',
      id    : 31838,
      el    : 'wpac-rating',
      color : 'fc6423'
    });
    (function() {
      if ('WIDGETPACK_LOADED' in window) return;
      WIDGETPACK_LOADED = true;
      var mc = document.createElement('script');
      mc.type = 'text/javascript';
      mc.async = true;
      mc.src = '//embed.widgetpack.com/widget.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mc, s.nextSibling);
    })();
  }
  </script>












  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '16c7d02bc3ca2bae3d85',
      clientSecret: 'bfda6fb671841e71f55e41fdd3fb794c8dbf40b2',
      repo        : 'duweiwang.github.io',
      owner       : 'duweiwang',
      admin       : ['duweiwang'],
      id          : 'bbb9f21e368da75eb759639e1d07438e',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : '45lTcsdp8QJNGsmN5wEaOtV5-gzGzoHsz',
      appKey     : 'QsK8vR7pb8w0M1eIk7QE50yF',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>


  <!-- 页面点击小红心 -->
  
        <script type="text/javascript" src="/js/love.js"></script>
  
</body>
</html>
